// https://www.lintcode.com/problem/binary-tree-path-sum/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */


public class Solution {
    /*
     * @param root: the root of binary tree
     * @param target: An integer
     * @return: all valid paths
     */
    public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
        // write your code here
        List<List<Integer>> ret = new ArrayList<>();
        _binaryTreePathSum(ret, new ArrayList<>(), root, target);
        return ret;
    }
    
    protected void _binaryTreePathSum(List<List<Integer>> ret, List<Integer> path, TreeNode node, int target) {
        if (node == null) {
            return;
        }
        path.add(node.val);
        if ((node.left == null) && (node.right == null)) { // 根节点
            if (node.val == target) {
                List<Integer> _path = new ArrayList<>();
                _path.addAll(path);
                ret.add(_path);
            }
        }
        if (node.left != null) {
            _binaryTreePathSum(ret, path, node.left, target - node.val);
            path.remove(path.size() - 1);
        }
        if (node.right != null) {
            _binaryTreePathSum(ret, path, node.right, target - node.val);
            path.remove(path.size() - 1);
        }
    }
}